<template>
  <!-- 主容器 -->
  <div class="home-container">
    <!-- 左边 -->
    <main class="left-content">
      <div class="movie-info" v-if="detailData.id">
        <h1 class="title">{{ detailData.title }} {{ detailData.original_title }} <span
            class="year">({{ detailData.year }})</span></h1>
        <!-- 简介 -->
        <div class="desc-content">
          <img :src="detailData.cover_url" class="mv-img">
          <div class="mv-desc">
            <p>导演：<a href="#"
                       v-if="detailData.directors && detailData.directors.length">{{ detailData.directors[0].name }}</a>
            </p>
            <p>主演：
              <a href="" v-for="(item, index) in actors.short" :key="index">{{ item.name }}
                <template v-if="index !== actors.short.length-1">/</template>
              </a>
              <span v-if="actors.isShowMore" class="more-actors" @click="expand">更多...</span>
              <span v-if="!actors.isShowMore" class="more-actors" @click="shrink">收起</span>
            </p>
            <p>类型：<span class="it">{{ detailData.genres.join(' / ') }}</span></p>
            <p>制片国家/地区：<span class="it">{{ detailData.countries.join(' / ') }}</span></p>
            <p>语言：<span class="it">{{ detailData.languages.join(' / ') }}</span></p>
            <p>上映日期：<span class="it">{{ detailData.pubdate.join(' / ') }}</span></p>
            <p>片长：<span class="it">{{ detailData.durations.join(' / ') }}</span></p>
            <p>又名：<span class="it">{{ detailData.aka.join(' / ') }}</span></p>
            <a :href="detailData.imdb" target="_blank">IMDb链接 <span class="it">{{
                detailData.imdb.split('/').pop()
              }}</span></a>
          </div>
          <div class="mv-rank">
            <div class="rank-title">豆瓣评分</div>
            <div class="rank-score">
              <div class="score"><strong class="num">{{ detailData.rating.value }}</strong></div>
              <div class="score-star">
                <Rankstar :score="detailData.rating.value" class="rankstar"></Rankstar>
                <div class="score-comment"><a href="#">{{ detailData.rating.count }}</a>人评价</div>
              </div>
            </div>
            <div class="score-rate">
              <div v-for="item in rate.list" class="rate-item" :key="item.index">
                <span>{{ item.index }}</span>
                <span class="wline" :style="{width:item.width+'px'}"></span>
                <span class="percent">{{ item.count.toFixed(1) }}%</span>
              </div>
            </div>
            <div class="better-content">
              <div v-for="(item, index) in rate.betterList" class="better-item">好于<a
                  href="#">{{ Math.round(item.rank * 100) }}%{{ item.type }}</a></div>
            </div>
          </div>
        </div>

        <!-- 评分写影评 -->
        <div class="opera-box">

          <div class="score-add button-container" v-if="favouriteMovie == null">
            <a href="javascript:void(0)" @click="openModal('我想看这部电影',ADD_WANT,WANT)" class="db-button">
              <span>想看</span>
            </a>
            <a href="javascript:void(0)" @click="openModal('我看过这部电影',ADD_SEEN,SEEN)" class="db-button">
              <span>看过</span>
            </a>
            <div class="review">评价：</div>
            <div class="rankstar">
              <div :class="['star-item', item.state]" v-for="(item, index) in starlist.list || []" :key="index"
                   @mouseenter="changeScore(index)"
                   @mouseleave="resetScore"
                   @click="openModal('我看过这部电影',ADD_SEEN,SEEN)">
              </div>
              {{ review }}
            </div>
          </div>
          <div v-else class="favourite-movie">
            <span class="favourite-movie-title">{{ favouriteMovie.title }}</span>
            <span
                class="favourite-movie-create-time">{{
                new Date(favouriteMovie.create_time).toISOString().split('T')[0]
              }}</span>
            <span class="btn-float"></span>
            <a href="javascript:void(0)" @click="editFavourite" class="edit-btn">
              <span>修改</span>
            </a>
            <a href="javascript:void(0)" @click="removeFavourite" class="del-btn">
              <span>删除</span>
            </a>
            <div class="rankstar" style="pointer-events: none" v-if="favouriteMovie.type === SEEN">
              <label>我的评价:</label>
              <div :class="['star-item', item.state]" v-for="(item, index) in favouriteMovie.rating.starlist || []"
                   :key="index"
              >
              </div>
              {{ review }}
            </div>
            <div class="tags-content">
              <label>标签：</label>
              <span v-for="genre in favouriteMovie.genres" class="tag-item">{{ genre }}</span>
            </div>
            <div>
              <label>简短评论：</label>
              <span>{{ favouriteMovie.abstract }}</span>
            </div>

          </div>
          <div class="publish">
            <img src="https://img3.doubanio.com/f/shire/5bbf02b7b5ec12b23e214a580b6f9e481108488c/pics/add-review.gif"
                 alt=""/>
            <a href="javascript:void(0)" class="comment-link" @click="goPublish"> 写影评</a>
          </div>
        </div>

        <!-- 剧情简介 -->
        <div class="intro">
          <h2 class="intro-title">
            {{ detailData.title }}的剧情简介......
          </h2>
          <div class="intro-content">
            {{ detailData.intro }}
          </div>
        </div>

        <!-- 弹出框 -->
        <keep-alive>
          <AddCollectionModal
              :genres="detailData.genres"
              :isVisible="showModal"
              @close="closeModal"
              :ranks="fixedstarlist.list"
              :title="modalTitle"
              :type="modalType"
              :favouriteMovie="favouriteMovie"
              :favouriteType="favouriteType"
          />
        </keep-alive>
      </div>
    </main>

    <!-- 右边 -->
    <aside class="right-content">
      <h2 class="intro-title">
        豆瓣成员常用的标签......
      </h2>
      <div class="tags-content">
        <div v-for="genre in detailData.genres" :key="genre" class="tag-item">{{ genre }}</div>
      </div>
      <h2 class="intro-title">
        以下豆瓣推荐......
      </h2>
      <div id="subject-doulist">
        <ul>
          <li v-for="(item, index) in recommendedLinks" :key="index">
            <a :href="item.url" target="_blank">{{ item.title }}</a>
            <span>({{ item.author }})</span>
          </li>
        </ul>
      </div>
      <h2 class="intro-title">
        谁在看这部电影......
      </h2>
      <div class="who-is-watching">
        <a href="javascript:void(0)">{{ detailData.rating?.count }}人看过</a>
        /
        <a href="javascript:void(0)">{{ detailData.rating?.count }}人想看</a>
      </div>
    </aside>
  </div>
</template>

<script setup>
import Rankstar from '@/components/rankstar/Rankstar.vue'
import {ADD_SEEN, ADD_WANT, EDIT, SEEN, WANT} from '@/constant/constant'
import DoubanApi from '@/api/douban'
import {useRoute, useRouter} from 'vue-router'
import {onMounted, computed, ref, reactive} from 'vue'
import {useStore} from 'vuex'
import AddCollectionModal from '@/components/modal/AddCollection.vue'

const store = useStore()
const route = useRoute()
const router = useRouter()
const userInfo = computed(() => store.state.userInfo)
const id = computed(() => route.query.id)

const favouriteMovie = computed(() => store.getters.getFavouriteMovieById(id.value))

let detailData = ref({})

let actors = reactive({
  origin: [],
  short: [],
  isShowMore: true
})


let rate = reactive({
  list: [],
  betterList: []
})


const starlist = reactive({
  list: new Array(5).fill({state: 'normal'})
})

const fixedstarlist = reactive({
  list: new Array(5).fill({state: 'normal'})
})


// 改变评分
const changeScore = (index) => {
  const list = []

  starlist.list.forEach((item, _index) => {
    if (_index <= index) {
      item.state = 'full'
    } else {
      item.state = 'normal'
    }

    list.push({...item})
  })

  starlist.list = list
}

// 重置评分
const resetScore = () => {
  starlist.list = starlist.list.map(item => ({state: 'normal'}))
}

// 评分
const review = computed(() => {
  const fullStars = starlist.list.filter(item => item.state === 'full').length
  switch (fullStars) {
    case 1:
      return '很差'
    case 2:
      return '较差'
    case 3:
      return '还行'
    case 4:
      return '推荐'
    case 5:
      return '力荐'
    default:
      return ''
  }
})

// 推荐链接
const recommendedLinks = ref([])

onMounted(async () => {
  await DoubanApi.getMovieDetail(id.value).then(res => {
    detailData.value = res
    store.commit('setTitle', detailData.value.title)
    actors.origin = detailData.value.actors || []
    actors.short = actors.origin.slice(0, 3)
    actors.isShowMore = actors.origin.length > 3
  })

  await DoubanApi.getMovieRatting(id.value).then(res => {
    const data = res
    rate.list = dealRateData(data)
    rate.betterList = data.type_ranks || []
  })

  recommendedLinks.value = [
    {url: 'https://www.douban.com/doulist/223781/', title: '【豆瓣高分动画长片】', author: '影志'},
    {url: 'https://www.douban.com/doulist/1504454/', title: 'ღ♩♪生活有这些期待很有动力♫♬ღ', author: 'freedom♪'},
    {url: 'https://www.douban.com/doulist/43556971/', title: '始终会看的电影', author: '可可'},
    {url: 'https://www.douban.com/doulist/1434921/', title: '2024—2027值得关注的华语电影', author: 'clover'},
    {url: 'https://www.douban.com/doulist/145327/', title: '事关自我本真之存在', author: '秋熙'}
  ]


})

const removeFavourite = () => {
  if (window.confirm('真的要删除这个收藏?')) {
    store.commit('deleteFavouriteMovie', id.value)
  }
}

const editFavourite = () => {
  openModal(modalTitle.value, EDIT, favouriteType.value)
}

const goPublish = () => {
  if (userInfo.value.username) {
    router.push('/publish?id=' + detailData.value.id)
  } else {
    router.push('/login')
  }
}


//排行预处理
const dealRateData = (rateData) => {
  let maxwidth = 70
  let list = []

  for (let i = 0; i < rateData.stats.length; i++) {
    let r = rateData.stats[i].toFixed(3) * 100
    list.push({
      index: i + 1,
      count: r,
      width: r * maxwidth / 100
    })
  }

  return list.reverse()
}

//展开所有名字
const expand = () => {
  actors.short = actors.origin
  actors.isShowMore = false
}

//收起
const shrink = () => {
  actors.short = actors.origin.slice(0, 3)
  actors.isShowMore = true
}

// 是否显示弹出框
const showModal = ref(false)
// 弹出框标题
const modalTitle = ref('')
// 弹出框类型
const modalType = ref('')
// 收藏类型
const favouriteType = ref('')

// 打开弹出框函数
const openModal = (title, type, fType) => {
  if (userInfo.value.username) {
    modalTitle.value = title
    modalType.value = type
    favouriteType.value = fType
    showModal.value = true
    fixedstarlist.list = starlist.list.map(item => ({...item}))
  } else {
    router.push('/login')
  }
}


const closeModal = () => {
  showModal.value = false
}

</script>

<style lang="less" scoped>
.home-container {
  display: flex;
  width: 1040px;
}

.left-content {
  width: 705px;
}

.right-content {
  width: 300px;
  margin-top: 45px;
  margin-left: 40px;
}

/* 收藏部分 */
.favourite-movie-create-time {
  padding-left: 10px;
  color: #999999;
}

.tags-content {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.tags-content label {
  color: #666;
}

/* 标签样式 */
.tag-item {
  padding: 1px 3px;
  font-size: 12px;
  background-color: rgba(115, 143, 199, 0.25);
  color: #37a;;
  font-weight: bold;
  transition: background-color 0.3s ease, color 0.3s ease;
  cursor: pointer;
  text-align: center;
}

.tag-item:hover {
  background-color: #37a;
  color: #fff;
}

.title {
  margin-top: 20px;
  font-size: 26px;
  font-weight: bold;
  color: #494949;

  .year {
    color: #888
  }
}

.desc-content {
  display: flex;
  margin-top: 13px;
}

.mv-img {
  width: 135px;
  height: 200px;
}

.mv-desc {
  font-size: 13px;
  margin-left: 15px;
  max-width: 450px;
  padding: 0 30px;

  p {
    margin: 2px 0;
    color: #666;

    .it {
      color: #111;
    }
  }
}

.more-actors {
  color: #aaa;
  cursor: pointer;

  &:hover {
    color: #fff;
    background-color: #aaa;
  }
}

.mv-rank {
  width: 155px;
  margin: 2px 0 0 0;
  padding: 0 0 0 15px;
  border-left: 1px solid #eaeaea;
  color: #9b9b9b;
}

.rank-score {
  margin-top: 5px;
  display: flex;

  .num {
    color: #494949;
    padding: 0;
    font-size: 28px;
  }
}

.review {
  margin-left: 10px;
}

.rankstar {
  display: flex;
  align-items: center;
}

.rankstar label {
  padding-right: 5px;
}

.score-star {
  margin-left: 10px;
  padding-top: 5px;

  .rankstar {
    transform: scale(1.3);
    transform-origin: 0 0;
  }
}


.score-add {
  margin-top: 10px;
  display: flex;
}

/* 按钮容器 */
.button-container {
  display: flex; /* 按钮和文字横向排列 */
  align-items: center; /* 垂直对齐 */
  gap: 8px; /* 按钮和文字之间的间距 */
}

/* 按钮样式 */
.db-button {
  display: inline-block;
  padding: 2px 6px; /* 缩小按钮的内边距 */
  font-size: 12px; /* 调整文字大小 */
  font-family: Arial, sans-serif;
  color: #000; /* 字体颜色 */
  text-align: center;
  text-decoration: none; /* 去除下划线 */
  background-color: #fbeee0; /* 浅色背景 */
  border: 1px solid #f5d8a8; /* 边框颜色 */
  border-radius: 3px; /* 圆角半径 */
  line-height: 1; /* 行高 */
  height: auto; /* 高度自适应内容 */
  transition: all 0.3s ease; /* 添加交互动画 */
}

/* 鼠标悬浮时效果 */
.db-button:hover {
  background-color: #f5d8a8; /* 背景颜色变深 */
  color: #000; /* 保持文字颜色 */
  border-color: #e4b97c; /* 边框颜色变深 */
}

.star-item {
  width: 16px;
  height: 16px;
  background-size: cover;
  cursor: pointer;

  &.normal {
    background-image: url('/imgs/star.png');
  }

  &.full {
    background-image: url('/imgs/star-fill.png');
  }
}

.score-comment {
  margin-top: 7px;
}

.rate-item {
  display: flex;
}

.wline {
  height: 10px;
  margin: 1px 4px;
  background: #ffd596 none repeat scroll 0 0;
  align-self: center;
}

.better-content {
  position: relative;
  padding: 10px 0;
  border-top: 1px solid #eaeaea;
  color: #9b9b9b;
  margin-top: 20px;
}

.better-item {
  margin-top: 1px;
}

.intro-title {
  margin: 24px 0 12px 0;
  font-size: 16px;
  color: #007722;
}

.favourite-action {
  display: flex; /* 按钮和文字横向排列 */
  align-items: center; /* 垂直对齐 */
  gap: 8px; /* 按钮和文字之间的间距 */
}

.btn-float {
  padding-left: 20px;
}

.edit-btn {
  cursor: pointer;
}

.del-btn {
  word-break: normal;
  word-wrap: break-word;
  font-family: inherit;
  font-style: inherit;
  font-weight: inherit;
  background: none;
  cursor: pointer;
  border: none;
  color: #bbb;
  vertical-align: baseline;
  margin-left: 7px;
}

.del-btn:hover {
  background: #999999;
  color: #FFFFFF;
}

.publish {
  margin-top: 10px;
}

.comment-link {
  font-size: 13px;
}

.interest_sect_level {
  display: inline-block;
}

.right-content {
  width: 300px;
  margin-left: 20px;
}

#subject-doulist {
  margin-top: 5px;
  border-top: 1px dashed #ddd;
}

#subject-doulist ul li {
  margin: 10px 0; /* Adjust the value as needed */
  border-bottom: 1px dashed #ddd;
}
</style>